package com.hfb.mashibing.alip8.juc.c020;


import java.util.concurrent.Exchanger;
import java.util.concurrent.Semaphore;

import static java.lang.Thread.currentThread;

/**
 * 交换器:允许2个线程之间交换数据,支持公平/非公平锁
 * 一般用于限流
 */

public class T12_TestExchanger {
    public static void main(String[] args) {
        // 允许2个线程之间交换数据
        Exchanger<String> exchanger = new Exchanger<String>();

        new Thread(()->{
            String s = "Thread1";
            try {
                // 获取信号量，此方法是阻塞方法
                s = exchanger.exchange(s);
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" "+s);
        },"T1").start();


        new Thread(()->{
            String s = "Thread2";
            try {
                // 获取信号量，此方法是阻塞方法
                s = exchanger.exchange(s);
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" "+s);
        },"T2").start();



    }
}
